package addition.nio;

import addition.utils.FileUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class BlockingNioDemo1 {

    @Test
    public void server() throws IOException {
        // 1. 创建通过
        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        // 2. 绑定端口
        ssChannel.bind(new InetSocketAddress(8080));

        // 3. 创建文件通道
        FileChannel inChannel = FileChannel.open(Paths.get("receive.jpg"),
                StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        // 4. 创建缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);

        // 5. 获取连接客户端
        SocketChannel sChannel = ssChannel.accept();

        // 6. 接收数据
        while (sChannel.read(buf) != -1) {
            buf.flip();
            inChannel.write(buf);
            buf.clear();
        }

        // 7. 关闭资源
        sChannel.close();
        inChannel.close();
        ssChannel.close();
    }

    @Test
    public void client() throws IOException {
        // 1. 创建通道并绑定连接
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));

        // 2. 创建文件通道
        FileChannel inChannel = FileChannel.open(Paths.get(FileUtils.getRootFilePath("wallhaven-z85gyw.jpg")),
                StandardOpenOption.READ);

        // 3. 创建缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);

        // 4. 写入数据
        while (inChannel.read(buf) != -1) {
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }

        // 5. 关闭资源
        inChannel.close();
        sChannel.close();
    }

}
